ErrorBoundary.componentDidCatch   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
c 0
b 0
f 0
ccs 2
cts 2
cp 1
rs 10
cc 1
crap 1
1 1
import React from "react";
2
3 1
import { Button } from "@cianciarusocataldo/modular-ui";
4
5
/** Modular error boundary, wrap all App components to intercept most of the errors thrown
6
 *
7
 * @param {() => JSX.Element} fallback custom fallback displayed when an error is catched
8
 *
9
 * @author Cataldo Cianciaruso <https://github.com/CianciarusoCataldo>
10
 *
11
 * @copyright 2022 Cataldo Cianciaruso
12
 */
13 1
class ErrorBoundary extends React.Component<
14
  { fallback?: () => JSX.Element },
15
  { hasError: boolean }
16
> {
17
  constructor(props) {
18 6
    super(props);
19 6
    this.state = { hasError: false };
20
  }
21
22 1
  static getDerivedStateFromError(error) {
23 1
    return { hasError: true };
24
  }
25
26 1
  componentDidCatch(error, errorInfo) {
27 1
    this.setState({
28
      hasError: true,
29
    });
30
  }
31
32 1
  render() {
33 8
    if (this.state.hasError) {
34 2
      window.document.title = "Error";
35 2
      return (
36
        this.props.fallback || (
37
          <div
38
            style={{
39
              width: "100vw",
40
              height: "100vh",
41
              display: "flex",
42
              flexDirection: "column",
43
            }}
44
          >
45
            <div style={{ margin: "auto" }}>
46
              <Button
47
                style={{ fontSize: "3rem", padding: "1rem" }}
48
                className="error-button"
49
                onClick={() => {
50 1
                  window.location.reload();
51
                }}
52
              >
53
                Try again
54
              </Button>
55
            </div>
56
          </div>
57
        )
58
      );
59
    }
60
61 6
    return this.props.children;
62
  }
63 1
}
64
65
export default ErrorBoundary;
66